/*
 * Copyright (c) 2017, Li Bo/Alex All rights reserved.
 * 
 * http://blog.sina.com.cn/alex4java
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package net.alex.jetty.exec.server;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import net.alex.jetty.bean.JettyRunConfigure;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.ContextHandlerCollection;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.xml.XmlConfiguration;

/**
 * @ClassName: JettyServerRunner
 * @Description:jetty 服务执行器操作 基于 server 包下
 * @author: 李博/Alex
 * @date: 2017-2-24 上午10:20:54
 * @email:  alexlibochn@china-pui.com.cn
 */
public final class JettyServerRunner {

	/**************系统默认端口：8080 缺省参数******************/
	private static final Integer DEFAULT_SERVER_PORT = 8080;
	
	/**************系统默认上下文路径：/ 缺省参数******************/
	private static final String DEFAULT_CONTEXT_PATH = "";

	/**************系统默认Jetty服务加载容器文件：默认当前路径下：./jetty/etc/webdefault.xml 缺省参数******************/
	private static final String DEFAULT_DESCRIPTOR = "jetty/etc/webdefault.xml";

	/**************系统默认Jetty服务加载Web资源文件：默认当前路径下：./WebRoot 缺省参数******************/
	private static final String DEFAULT_RESOURCE_BASE = "./WebRoot";
	
	/**************系统默认./etc/jetty.xml文件的路径：jetty.xml文件的路径 缺省参数******************/
	private static final String DEFAULT_JETTY_XML_PATH = "./etc/jetty.xml";
	
	//cancel the singleton model create Runner Object to support the exec
	//private static JettyServerRunner runner = new JettyServerRunner(); 
	
	private final Lock lock = new ReentrantLock();
	
	/**
	 * @Title: newInstance
	 * @Description: 执行创建 net.alex.jetty.exec.JettyServerRunner 对象
	 * @return
	 * @return: JettyServerRunner
	 */
	public static JettyServerRunner newInstance(){ return new JettyServerRunner();}
	
	/**
	 * @Title: start
	 * @Description:启动服务(默认启动的是所有默认参数)
	 * @return
	 * @return: boolean
	 */
	public boolean start(){
		lock.lock();
		//创建jettyServer对象
		Server server = new Server();
		//创建Connector组建
		Connector connector = new SelectChannelConnector();
		//Connector connector = new SocketConnector();
		connector.setPort(DEFAULT_SERVER_PORT);
		server.addConnector(connector);
		//创建Jetty服务上下文
		WebAppContext webAppContext = new WebAppContext();
		webAppContext.setContextPath(DEFAULT_CONTEXT_PATH);
		//webAppContext.setDescriptor(DEFAULT_DESCRIPTOR);
		webAppContext.setResourceBase(DEFAULT_RESOURCE_BASE);
		server.setHandler(webAppContext);
		//启动服务
		try {
			server.start();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally{
			lock.unlock();
		}
		return true;
	}
	
	/**
	 * @Title: start
	 * @Description:启动服务（启动的是所有指定的参数）
	 * @param configure
	 * @return
	 * @return: boolean
	 */
	public boolean start(JettyRunConfigure configure){
		if(configure == null )
			throw new NullPointerException("传入的参数JettyRunConfigure为空!");
		lock.lock();
		//创建jettyServer对象
		Server server = new Server();
		//创建Connector组建
		Connector connector = new SelectChannelConnector();
		connector.setPort(configure.getPort());
		server.addConnector(connector);
		//创建Jetty服务上下文
		WebAppContext webAppContext = new WebAppContext();
		webAppContext.setContextPath(configure.getContextPath());
		//webAppContext.setDescriptor(configure.getDefaultsDescriptor());
		webAppContext.setResourceBase(configure.getDeployResourceBasePath());
		server.setHandler(webAppContext);
		//启动服务
		try {
			server.start();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally{
			lock.unlock();
		}
		return true;
	}
	
	/**
	 * @Title: start
	 * @Description: 启动服务（启动的是所有指定的参数）启动所有参数对的服务其中会做校验端口是否已绑定
	 * @param configures
	 * @return
	 * @return: boolean
	 */
	public boolean start(List<JettyRunConfigure> configures){
		
		for(JettyRunConfigure configure:configures){
			try{
				start(configure);
			}catch(Exception e){
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/**
	 * @Title: start
	 * @Description: 启动服务(只需指定对应绝对路径的jetty.xml文件即可)
	 * @param jettyXmlPath
	 * @return
	 * @return: boolean
	 */
	public boolean start(String jettyXmlPath){
		Server server = new Server();
		jettyXmlPath = (jettyXmlPath != null)?jettyXmlPath:DEFAULT_JETTY_XML_PATH;
		try {
			XmlConfiguration configure = new XmlConfiguration(jettyXmlPath);
			configure.configure(server);
			server.start();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	
	
	public static void main(String[] args) {
		Server server = new Server();
		try {
			Connector conn = new SocketConnector();
			conn.setPort(9999);
			server.setConnectors(new Connector[]{conn});
			
			ContextHandlerCollection handler = new ContextHandlerCollection();
			/*ServletContextHandler servlethandler = new ServletContextHandler();
			//servlethandler.addServlet(MyServlet.class, "*.do");
			handler.addHandler(servlethandler);*/
			WebAppContext webapp = new WebAppContext();
			webapp.setContextPath("/123");
			webapp.setResourceBase("/Users/alex/Documents/我的代码/webManager/WebRoot");
           // webapp.setDefaultsDescriptor("./jetty/etc/webdefault.xml");
			handler.addHandler(webapp);
			
			server.setHandler(handler);
			
			XmlConfiguration conf = new XmlConfiguration("jetty/etc/jetty.xml");
			conf.configure(server);
			server.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
